package main

import (
	"fmt"
	"math/rand"
	"net/http"
	"time"
)

var (
	n      = 10
	result []int
)

type worker struct {
	in  chan int
	out chan int
}

func doWork(id int) worker {
	w := worker{
		in:  make(chan int),
		out: make(chan int),
	}
	go func() {
		for n := range w.in {
			time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
			w.out <- n
			fmt.Printf("from %c\n", n)
		}
	}()
	return w
}

func work() []int {
	var workers [10]worker
	for i := 0; i < n; i++ {
		workers[i] = doWork(i)
	}
	for i := 0; i < n; i++ {
		workers[i].in <- 'a' + i
	}
	for i := 0; i < n; i++ {
		result = append(result, <-workers[i].out)
	}
	return result
}

func AHandler(w http.ResponseWriter, r *http.Request) {
	for _, v := range work() {
		fmt.Fprintf(w, "C serviece%c", v)
	}
}

func main() {
	http.HandleFunc("/", AHandler)
	http.ListenAndServe("0.0.0.0:8089", nil)
}
